package com.jstyle.beatecg.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jstyle.beatecg.R;
import com.jstyle.beatecg.daoManager.HrvDataDaoManager;
import com.jstyle.beatecg.model.HrvData;
import com.jstyle.beatecg.util.ChartDataUtil;

import java.util.HashMap;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HealthHistoryFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HealthHistoryFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.history_linechart_avgHeart)
    LineChartView historyLinechartAvgHeart;
    @BindView(R.id.history_ColumnChart_heartError)
    ColumnChartView historyColumnChartHeartError;
    @BindArray(R.array.week)
    String[] arrayWeek;
    int right = 7;
    Unbinder unbinder;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public HealthHistoryFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HealthHistoryFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HealthHistoryFragment newInstance(String param1, String param2) {
        HealthHistoryFragment fragment = new HealthHistoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_health_history, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        String[] axisArray = getAxiesArray();
        int length = axisArray.length;
        if (length == 1) {
            updateDayChart(axisArray);
        } else {
            updateWeekOrMonthChart(axisArray, length);
        }
    }

    private void updateDayChart(String[] axisArray) {
        List<HrvData> hrvDataList= HrvDataDaoManager.getHrvData(axisArray[0],axisArray[0]);

        int size=hrvDataList.size();
        ChartDataUtil.initChartView(historyLinechartAvgHeart, 0f, 170, size, 30);
        ChartDataUtil.initChartView(historyColumnChartHeartError, -0.5f, 11f, size, 0);

        historyLinechartAvgHeart.setLineChartData( ChartDataUtil.getDayAvgHeartChart(getActivity(), hrvDataList));
        historyColumnChartHeartError.setColumnChartData(ChartDataUtil.getDayHeartErrorColumnChart(getActivity(), hrvDataList));
        ChartDataUtil. settingXb(size,historyLinechartAvgHeart);
        ChartDataUtil. settingXb(size,historyColumnChartHeartError);
    }

    private void updateWeekOrMonthChart(String[] axisArray, int length) {
        List<HrvData> hrvDataList = HrvDataDaoManager.getHrvData(axisArray[0], axisArray[length - 1]);
        HashMap<String, Integer> maxHashMap = new HashMap<>();
        HashMap<String, Integer> minHashMap = new HashMap<>();
        HashMap<String, Integer> errorHashMap = new HashMap<>();
        for (HrvData hrvData : hrvDataList) {
            String time = hrvData.getTime().split(" ")[0];
            int hrvMax = hrvData.getMaxHeart();
            int hrvMin = hrvData.getMinHeart();
            int errorData = hrvData.getError();
            Integer max = maxHashMap.get(time);
            maxHashMap.put(time, max == null ? hrvMax : Math.max(max, hrvMax));
            Integer min = minHashMap.get(time);
            minHashMap.put(time, min == null ? hrvMin : Math.min(min, hrvMin));
            Integer error = errorHashMap.get(time);
            errorHashMap.put(time, error == null ? errorData : error + errorData);

        }
        ChartDataUtil.initChartView(historyLinechartAvgHeart, -0.5f, 170, length - 0.5f, 30);
        ChartDataUtil.initChartView(historyColumnChartHeartError, -0.5f, 11, length - 0.5f, 0);
        LineChartData lineChartData = ChartDataUtil.getAvgHeartChart(getActivity(), axisArray, maxHashMap, minHashMap);
        historyLinechartAvgHeart.setLineChartData(lineChartData);
        historyColumnChartHeartError.setColumnChartData(ChartDataUtil.getHeartErrorColumnChart(getActivity(), axisArray, errorHashMap));

    }

    private String[] getAxiesArray() {
        InfoFragment infoFragment = (InfoFragment) getParentFragment();
        int dateType = infoFragment.dateType;
        String[] axisArray = null;
        switch (dateType) {
            case 0:
                axisArray = new String[1];
                axisArray[0] = infoFragment.getTodayString();
                break;
            case 1:
                axisArray = infoFragment.getThisWeek();
                break;
            case 2:
                axisArray = infoFragment.getMonthDate();
                break;
        }
        return axisArray;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Fragment fragment = getParentFragment();
        Log.i(TAG, "onAttach: " + fragment.toString());
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    private static final String TAG = "HealthHistoryFragment";

    @Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (this.getView() != null) {
            this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
        }
        Log.i(TAG, "setMenuVisibility: ");
        if (menuVisible && isAdded()) initView();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    public void updateData() {
        initView();
        Log.i(TAG, "updateData: ");
    }
}
